package com.yupi.yuoj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.yuoj.common.ErrorCode;
import com.yupi.yuoj.constant.CommonConstant;
import com.yupi.yuoj.exception.ThrowUtils;
import com.yupi.yuoj.model.dto.membershiporder.MembershipOrderQueryRequest;
import com.yupi.yuoj.model.entity.MembershipOrder;
import com.yupi.yuoj.model.entity.User;
import com.yupi.yuoj.model.vo.MembershipOrderVO;
import com.yupi.yuoj.model.vo.UserVO;
import com.yupi.yuoj.service.MembershipOrderService;
import com.yupi.yuoj.mapper.MembershipOrderMapper;
import com.yupi.yuoj.service.UserService;
import com.yupi.yuoj.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @author admin
* @description 针对表【membership_order(浼氬憳璁㈠崟琛)】的数据库操作Service实现
* @createDate 2025-11-01 21:28:42
*/
@Service
public class MembershipOrderServiceImpl extends ServiceImpl<MembershipOrderMapper, MembershipOrder>
    implements MembershipOrderService{

    @Resource
    private UserService userService;

    @Override
    public void validMembershipOrder(MembershipOrder membershipOrder, boolean add) {
        if (membershipOrder == null) {
            throw new RuntimeException("会员订单不能为空");
        }
        String planId = membershipOrder.getPlanId();
        Long userId = membershipOrder.getUserId();
        String status = membershipOrder.getOrderStatus();

        // 创建时，参数不能为空
        if (add) {
            ThrowUtils.throwIf(StringUtils.isAnyBlank(planId), ErrorCode.PARAMS_ERROR);
            ThrowUtils.throwIf(ObjectUtils.anyNull(userId), ErrorCode.PARAMS_ERROR);
        }
        // 有参数则校验
        if (StringUtils.isNotBlank(planId) && planId.length() > 80) {
            throw new RuntimeException("计划ID过长");
        }
        if (StringUtils.isNotBlank(status) && status.length() > 20) {
            throw new RuntimeException("状态过长");
        }
    }

    @Override
    public QueryWrapper<MembershipOrder> getQueryWrapper(MembershipOrderQueryRequest membershipOrderQueryRequest) {
        QueryWrapper<MembershipOrder> queryWrapper = new QueryWrapper<>();
        if (membershipOrderQueryRequest == null) {
            return queryWrapper;
        }
        Long membershipPlanId = membershipOrderQueryRequest.getMembershipPlanId();
        Long userId = membershipOrderQueryRequest.getUserId();
        String status = membershipOrderQueryRequest.getStatus();
        String sortField = membershipOrderQueryRequest.getSortField();
        String sortOrder = membershipOrderQueryRequest.getSortOrder();

        // 拼接查询条件
        queryWrapper.eq(ObjectUtils.isNotEmpty(membershipPlanId), "planId", membershipPlanId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(StringUtils.isNotBlank(status), "status", status);
        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    @Override
    public MembershipOrderVO getMembershipOrderVO(MembershipOrder membershipOrder, HttpServletRequest request) {
        MembershipOrderVO membershipOrderVO = new MembershipOrderVO();
        BeanUtils.copyProperties(membershipOrder, membershipOrderVO);

        // 1. 关联查询用户信息
        Long userId = membershipOrder.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        membershipOrderVO.setUser(userVO);

        return membershipOrderVO;
    }

    @Override
    public Page<MembershipOrderVO> getMembershipOrderVOPage(Page<MembershipOrder> membershipOrderPage, HttpServletRequest request) {
        List<MembershipOrder> membershipOrderList = membershipOrderPage.getRecords();
        Page<MembershipOrderVO> membershipOrderVOPage = new Page<>(membershipOrderPage.getCurrent(), membershipOrderPage.getSize(), membershipOrderPage.getTotal());
        if (membershipOrderList.isEmpty()) {
            return membershipOrderVOPage;
        }
        // 1. 关联查询用户信息
        Set<Long> userIdSet = membershipOrderList.stream().map(MembershipOrder::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));

        // 填充信息
        List<MembershipOrderVO> membershipOrderVOList = membershipOrderList.stream().map(membershipOrder -> {
            MembershipOrderVO membershipOrderVO = new MembershipOrderVO();
            BeanUtils.copyProperties(membershipOrder, membershipOrderVO);
            Long userId = membershipOrder.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            membershipOrderVO.setUser(userService.getUserVO(user));
            return membershipOrderVO;
        }).collect(Collectors.toList());
        membershipOrderVOPage.setRecords(membershipOrderVOList);
        return membershipOrderVOPage;
    }
}




